#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);    

    ui->OpenPortBtn->setEnabled(true);

    ui->ClosePortBtn->setEnabled(false);

    ui->SendMsgBtn->setEnabled(false);

    ui->ReadMsgBtn->setEnabled(false);

    ui->ResetTextBtn->setEnabled(true);

    ui->TextRead->setReadOnly(true);
}

void MainWindow::OpenPort(const QString & name, const PortSettings& settings, QextSerialBase::QueryMode mode)
{
    myPort = new Win_QextSerialPort(name,settings,mode);

    myPort->open(QIODevice::ReadWrite);
}

void MainWindow::ClosePort()
{
    myPort->close();
}

void MainWindow::WritePort(const QByteArray & name)
{
    myPort->write(name.constData());
}

QByteArray MainWindow::ReadPort()
{
    QByteArray buf=myPort->readAll();
    return buf;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_SendMsgBtn_clicked()
{
    this->WritePort(ui->TextWrite->toPlainText().toAscii());
}

void MainWindow::on_ReadMsgBtn_clicked()
{
    QString str=this->ReadPort();
    ui->TextRead->setText(str);
}

void MainWindow::on_OpenPortBtn_clicked()
{
    struct PortSettings myPortSetting = {BAUD38400,DATA_8,PAR_NONE,STOP_1,FLOW_OFF,500};

    this->OpenPort("com1",myPortSetting,QextSerialBase::EventDriven);

    ui->OpenPortBtn->setEnabled(false);

    ui->ClosePortBtn->setEnabled(true);

    ui->SendMsgBtn->setEnabled(true);

    ui->ReadMsgBtn->setEnabled(true);
}

void MainWindow::on_ResetTextBtn_clicked()
{
    ui->TextRead->setText("");
    ui->TextWrite->setText("");
}

void MainWindow::on_ClosePortBtn_clicked()
{
    this->ClosePort();

    ui->ReadMsgBtn->setEnabled(false);

    ui->SendMsgBtn->setEnabled(false);

    ui->ClosePortBtn->setEnabled(false);

    ui->OpenPortBtn->setEnabled(true);
}
